package com.simp.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.simp.entity.SysCategoryEntity;
import com.simp.entity.SysConfigEntity;
import com.simp.expection.GlobalException;
import com.simp.mapper.SysCategoryMapper;
import com.simp.model.SysCategoryModel;
import com.simp.page.R;
import com.simp.utils.BeanConvertUtils;
import com.simp.vo.TreeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author pan.shun
 * @version 2.0
 * @since 2022/3/24 19:34
 */
@Slf4j
@Service
public class SysCategoryService extends ServiceImpl<SysCategoryMapper, SysCategoryEntity> {

    /**
     * 获取种类树
     */
    public R getTreeList(String tableName) {
        LambdaQueryWrapper<SysCategoryEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysCategoryEntity::getTableName, tableName);
        queryWrapper.orderByAsc(SysCategoryEntity::getCreateTime);
        List<SysCategoryEntity> list = this.list(queryWrapper);

        if (CollectionUtils.isEmpty(list)) {
            SysCategoryEntity rootNode = new SysCategoryEntity();
            rootNode.setLabel("根节点");
            rootNode.setParentId("0");
            rootNode.setTableName(tableName);
            list.add(rootNode);
        }

        List<SysCategoryModel> treeList = new ArrayList<>();

        list.forEach(r -> {
            SysCategoryModel convert = BeanConvertUtils.convert(r, SysCategoryModel.class);
            treeList.add(convert);
        });
        transToTree(treeList);
        treeList.removeIf(next -> !"0".equals(next.getParentId()));
        return R.success(treeList);
    }

    public void transToTree(List<? extends TreeVo> voList) {
        Map<String, TreeVo> voMap = Maps.newHashMap();
        voList.forEach((vox) -> {
            voMap.put(vox.getId(), vox);
        });
        Iterator var3 = voList.iterator();

        while (var3.hasNext()) {
            TreeVo vo = (TreeVo) var3.next();
            if (!"0".equals(vo.getParentId())) {
                TreeVo parentVo = (TreeVo) voMap.get(vo.getParentId());
                if (parentVo != null) {
                    vo.setParentName(parentVo.getName());
                    List<TreeVo> children = parentVo.getChildren();
                    if (children == null) {
                        children = Lists.newArrayList();
                        parentVo.setChildren((List) children);
                    }

                    ((List) children).add(vo);
                }
            }
        }

    }


    /**
     * 种类新增与修改
     */
    public R addOrUpdateCategory(SysCategoryEntity sysCategoryEntity) {
        if (StringUtils.isEmpty(sysCategoryEntity.getParentId())) {
            sysCategoryEntity.setParentId("0");
        }
        if (StringUtils.isEmpty(sysCategoryEntity.getId())) {
            this.save(sysCategoryEntity);
        } else {
            this.updateById(sysCategoryEntity);
        }
        return R.success();
    }

    /**
     * 种类删除
     */
    public R removeCategory(String id) {
        SysCategoryEntity sysCategory = this.getById(id);
        if (null == sysCategory) {
            throw new GlobalException("当前节点ID不存在");
        }
        ifHasChildrenNode(id, sysCategory.getTableName());
        this.removeById(id);
        return R.success();
    }

    private void ifHasChildrenNode(String pid, String tableName) {
        LambdaQueryWrapper<SysCategoryEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysCategoryEntity::getParentId, pid);
        queryWrapper.eq(SysCategoryEntity::getTableName, tableName);
        int count = this.count(queryWrapper);
        if (count != 0) {
            throw new GlobalException("当前节点其下有子节点，无法删除");
        }
    }
}
